"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
import json

from .models import *
from siriuso.forms.widgets import LingvoInputWidget
from universo_bazo.models import Realeco
from siriuso.utils.admin_mixins import TekstoMixin


# Форма типов звёздных систем в Универсо
class KosmoStelsistemoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KosmoStelsistemoTipo
        fields = [field.name for field in KosmoStelsistemoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы звёздных систем в Универсо
@admin.register(KosmoStelsistemoTipo)
class KosmoStelsistemoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KosmoStelsistemoTipoFormo
    list_display = ('nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KosmoStelsistemoTipo


# Форма звёздных систем в Универсо
class KosmoStelsistemoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KosmoStelsistemo
        fields = [field.name for field in KosmoStelsistemo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Звёздные системы в Универсо
@admin.register(KosmoStelsistemo)
class KosmoStelsistemoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KosmoStelsistemoFormo
    list_display = ('nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KosmoStelsistemo


# Форма Кубы (ячейки, чанки) звёздных систем в Универсо
class KosmoStelsistemoKuboFormo(forms.ModelForm):
    
    class Meta:
        model = KosmoStelsistemoKubo
        fields = [field.name for field in KosmoStelsistemoKubo._meta.fields if field.name not in ('krea_dato', 'uuid')]


# Кубы (ячейки, чанки) звёздных систем в Универсо
@admin.register(KosmoStelsistemoKubo)
class KosmoStelsistemoKuboAdmin(admin.ModelAdmin, TekstoMixin):
    form = KosmoStelsistemoKuboFormo
    list_display = ('uuid','stelsistemo')
    exclude = ('uuid',)
    class Meta:
        model = KosmoStelsistemoKubo


